<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert
        title="警告:只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        :show-icon="true">
      </el-alert>
      <!-- 选择商品分类视图 -->
      <el-row class="row_cate_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择器 -->
          <el-cascader
            :options="cateList"
            :props="cateProps"
            v-model="selectedKeys"
            @change="cascaderChange"
            clearable>
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab视图 -->
      <el-row>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <!-- 动态参数tab -->
          <el-tab-pane label="动态参数" name="many">
            <el-button size="mini" type="primary" :disabled="isBtnDisable" @click="addParamsDialogVisible=true">添加参数</el-button>
            <!-- 动态参数表格 -->
            <el-table :data="manyTableData" border stripe>
              <!-- 可扩展行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable  @close="handelTagClosed(i,scope.row)">{{item}}</el-tag>
                  <!-- 添加参数属性tag -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column label="#" type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParams(scope.row.attr_id)">编辑</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParam(scope.row.attr_id)">删除</el-button>
                </template>

              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 静态属性tab -->
          <el-tab-pane label="静态属性" name="only">
             <el-button size="mini" type="primary" :disabled="isBtnDisable" @click="addParamsDialogVisible=true">添加属性</el-button>
            <!-- 静态属性表格 -->
            <el-table :data="onlyTableData" border stripe>
              <!-- 可扩展行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable  @close="handelTagClosed(i,scope.row)">{{item}}</el-tag>
                  <!-- 添加参数属性tag -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column label="#" type="index"></el-table-column>
              <el-table-column label="静态属性" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParams(scope.row.attr_id)">编辑</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParam(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addParamsDialogClosed">
      <el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="editParamsDialogClosed">
      <el-form :model="editParamsForm" :rules="editParamsRules" ref="editParamsRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// a:调用接口，获取商品分类数据列表
// b:控制级联选择器的选择范围
// c：控制按钮的启用和禁用
// d:调用接口，获取参数列表
// e：添加属性对话框的添加，和基本布局渲染
// f:通过调用接口，完成参数的添加
// g:编辑参数功能实现
// h:删除动态参数或静态属性
// i:给可扩展行添加数据
// k:扩展行添加数据
// l:调用接口，完成扩展行可选参数的添加
// m:删除扩展行可选项
export default {
  data() {
    return {
      cateList: [],
      // 级联选择器配置对象
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联选择器选中数组
      selectedKeys: [],
      // tab栏配置对象
      // d2:修改activeName的值，使符合接口参数
      activeName: 'many',
      // 参数列表数据
      manyTableData: [],
      onlyTableData: [],
      addParamsDialogVisible: false,
      // 添加参数表单配置对象
      addParamsForm: {
       attr_name: ''
      },
      addParamsRules: {
        attr_name: [
          { required: true, message: '属性名称不能为空', trigger: 'blur' }
        ]
      },
      // 修改弹框配置信息
      editParamsDialogVisible: false,
      editParamsForm: {
         attr_name: ''
      },
      editParamsRules: {
         attr_name: [
          { required: true, message: '属性名称不能为空', trigger: 'blur' }
        ]
      }
      // 扩展行配置对象

    }
  },
  created() {
    // a1：在created阶段调用方法
    this.getCateList()
  },
  methods: {
    async getCateList() {
      // a2:调用接口
      const { data: res } = await this.$html.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败！')
      }
      // 获取数据成功
      this.cateList = res.data
    },
    // 监听级联选择器的变化
    cascaderChange() {
      this.getParamsData()
    },
    // 监听tab栏别点击
    handleTabClick() {
      this.getParamsData()
    },
    async getParamsData() {
      // b1：通过对数组长度判断
      if (this.selectedKeys.length !== 3) {
         // 清空数组
         this.selectedKeys = []
         this.manyTableData = []
         this.onlyTableData = []
         return false
      }
      // d3：调用接口获取参数列表
      const { data: res } = await this.$html.get(`categories/${this.cateID}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表数据失败！')
      }
      // 获取参数列表成功
      // i1:将res.data.attr_vals的字符串装换成数组,便于渲染
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 监听添加参数弹框的关闭
    addParamsDialogClosed() {
      this.$refs.addParamsRef.resetFields()
    },
    // 对动态添加参数确认按钮进行监听
    confirmAddParams() {
      // f1:对表单进行预校验
      this.$refs.addParamsRef.validate(async valid => {
        if (!valid) return false
        // f2：预校验通过，调用接口完成添加参数
        const { data: res } = await this.$html.post(`categories/${this.cateID}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败！')
        }
        // 添加参数成功
        this.$message.success('添加参数成功')
        this.getParamsData()
        this.addParamsDialogVisible = false
      })
    },
    // 对编辑按钮进行监听
    async editParams(attrId) {
      // g1:调用接口，获取要编辑的参数
      const { data: res } = await this.$html.get(`categories/${this.cateID}/attributes/${attrId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数数据错误!')
      }
      // 获取数据成功
      this.editParamsForm = res.data
      this.editParamsDialogVisible = true
    },
    // 对修改参数弹框关闭进行监听
    editParamsDialogClosed() {
      this.$refs.editParamsRef.resetFields()
    },
    // 对确认修改参数确认按钮进行监听
     confirmEditParams() {
      this.$refs.editParamsRef.validate(async valid => {
        if (!valid) {
          return false
        }
      // 预校验通过
      // g2:获取修改参数需要的参数，并调用接口
      const { data: res } = await this.$html.put(`categories/${this.cateID}/attributes/${this.editParamsForm.attr_id}`, {
        attr_name: this.editParamsForm.attr_name,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败！')
      }
      // 修改参数成功
      this.getParamsData()
      this.$message.success('修改参数成功！')
      this.editParamsDialogVisible = false
      })
    },
    // h1:对删除按参数按钮进行监听
    async removeParam(attrID) {
        const confirmRst = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        if (confirmRst !== 'confirm') {
          return this.$message.info('删除操作已经取消！')
        }
        // 确认删除
        // h2：调用接口
        const { data: res } = await this.$html.delete(`categories/${this.cateID}/attributes/${attrID}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除参数失败！')
        }
        this.$message.success('删除参数成功！')
        this.getParamsData()
    },
    // 可扩展行方法
    // 监听：添加tag输入框失去焦点
    async handleInputConfirm(row) {
      // tab中输入的数据如果不合法需要清空
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      // l1:输入tab的内容合法，先将输入的内容保存到数组中
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      // l2:调用接口，完成参数可选属性的添加
       this.uploadAttrvals(row)
    },
    async uploadAttrvals(row) {
      const { data: res } = await this.$html.put(`categories/${this.cateID}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('参数可选属性修改失败！')
      }
      this.$message.success('参数可选属性修改成功')
    },
    // 监听：+new tag被点击
    showInput(row) {
      row.inputVisible = true
      // $nextTick（）方法：当页面被重新渲染后，调用回调函数中的方法
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 监听：扩展行可选参数tag的关闭
    handelTagClosed(index, row) {
      console.log(row)
      // m1:根据索引删除对应的tag
      row.attr_vals.splice(index, 1)
      // m2：调用接口，实现attr_vals的上传，即：数据的保存
      this.uploadAttrvals(row)
    }
  },
  // 计算属性
  computed: {
    // c1：创建方法，返回boolean值确定按钮的禁用和使用
    isBtnDisable() {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      // 如果数组的涨肚等于三，则返回false，不禁用按钮
      return false
    },
    // d1:获取分类id
    cateID() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // e1：计算添加参数弹框的标题
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.row_cate_opt {
  margin:15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>